package cn.edu.zju.om.analyse;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Phrase {
	
	private String headTerm;
	
	private Map<String, Modifier> modifiers;
	
	public Phrase(String headTeamName, String modifierName, float rating) {
		this.headTerm = headTeamName;
		
		modifiers = new HashMap<String, Modifier>();
		Modifier modifer = new Modifier(modifierName, rating);
		modifiers.put(modifierName, modifer);
	}
	
	public String getHeadTerm() {
		return headTerm;
	}
	
	public Map<String, Modifier> getModifiers() {
		return modifiers;
	}
	
	public int getCount() {
		int count = 0;
		for(Entry<String, Modifier> entry : modifiers.entrySet()) {
			 Modifier modifier = entry.getValue();
			 count += modifier.getCount();
		}
		
		return count;
	}
	
	public float getAverageRating() {
		double sum = 0;
		int count = 0;
		for(Entry<String, Modifier> entry : modifiers.entrySet()) {
			 Modifier modifier = entry.getValue();
			 count += modifier.getCount();
			 sum += modifier.getCount() * modifier.getAverageRating();
		}
		
		return (float) sum / count;
	}
	
	public void update(String modifierName, float rating) {
		Modifier modifier = modifiers.get(modifierName);
		if (modifier != null) {
			modifier.update(rating);
		}
		else {
			modifier = new Modifier(modifierName, rating);
			this.modifiers.put(modifierName, modifier);
		}
	}
	
	public String toString() {
		StringBuilder ret = new StringBuilder();
		
		ret.append(String.format("%s\t%d\t%f", headTerm, getCount(), getAverageRating()));
		
		List<Modifier> modifierList = new ArrayList<Modifier>();
		
		for(Entry<String, Modifier> entry : modifiers.entrySet()) {
			Modifier modifier = entry.getValue();
			modifierList.add(modifier);
			//ret.append(", " + modifier.toString());
		}
		
		Collections.sort(modifierList, new Comparator<Modifier>() {
		
			public int compare(Modifier o1, Modifier o2) {
				return o2.getCount() - o1.getCount();
			}
		});
		
		for(Modifier modifier : modifierList) {
			ret.append("\t" + modifier.toString());
		}
		
		return ret.toString();
	}

}
